package com.tencent.cloud.uikit.widget.edittext;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 字符输入过滤器（限制中英混输入长度）
 *
 * 中文占 2 位
 * 英文占 1 位
 *
 */
public class SketchLengthFilter implements InputFilter {

    // 英文字符 ASCII 码最大值（中文及中文符号的 ASCII 值都大于 128）
    private static final int MAX_ENGLISH_ASCII_VALUE = 128;

    private static final int DEFAULT_MAX_LENGTH = 25;

    private final int mMaxLength;

    public SketchLengthFilter() {
        this(DEFAULT_MAX_LENGTH);
    }

    public SketchLengthFilter(int maxLength) {
        mMaxLength = maxLength;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int dindex = 0;
        int count = 0;

        while (count <= mMaxLength && dindex < dest.length()) {
            char c = dest.charAt(dindex++);
            if (isEnglishCharacter(c)) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }

        if (count > mMaxLength) {
            return dest.subSequence(0, dindex - 1);
        }

        int sindex = 0;
        while (count <= mMaxLength && sindex < source.length()) {
            char c = source.charAt(sindex++);
            if (isEnglishCharacter(c)) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }

        if (count > mMaxLength) {
            sindex--;
        }

        return source.subSequence(0, sindex);
    }

    /**
     * 是否英文字符
     *
     * @param c
     * @return
     */
    private boolean isEnglishCharacter(char c) {
        return c < MAX_ENGLISH_ASCII_VALUE;
    }

}